import Vue from 'vue'
// import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
// import iView from 'iview'
import { setToken, getToken, canTurnTo, setTitle } from '@/libs/util'
import config from '@/config'
const { homeName } = config

Vue.use(VueRouter)
const router = new VueRouter({
  routes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'

const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

const white_list = ['/login', '/register', '/forgetPwd', '/resetPwd'] // 未登录可防问
const white_code_list = [
  'dashboard',
  'login',
  'forget',
  'error_404',
  'error_401',
  'setting',
  'home',
  'ownspace_index',
  'message_page',
  'error_logger_page'
]   

router.beforeEach((to, from, next) => {
  iview.LoadingBar.start()
  if (getToken()) {
    // console.log('store.getters.user', typeof store.getters.user)
    if (store.getters.user === null || typeof store.getters.user.permissionList === 'undefined') {
      // 没有用户信息，获取用户信息
      store.dispatch('getUserInfo').then(res => {
        let PERMISSIONLIST = store.getters.user.permissionList
        white_code_list.forEach(ele => {
          PERMISSIONLIST.push(ele)
        })
        let hasPermission = PERMISSIONLIST.includes(to.name)

        if (hasPermission) {
          next()
        } else {
          next({
            name: 'error_401',
            meta: {
              title: '你还没有查看该页面的权限'
            }
          })
        }
      })
    } else {
      // 有用户信息
      let PERMISSIONLIST = store.getters.user.permissionList
      //   console.log('PERMISSIONLIST', PERMISSIONLIST)
      white_code_list.forEach(ele => {
        PERMISSIONLIST.push(ele)
      })
      let hasPermission = PERMISSIONLIST.includes(to.name)
      if (hasPermission) {
        next()
      } else {
        next({
          name: 'error_401',
          meta: {
            title: '你还没有查看该页面的权限'
          }
        })
      }
    }
  } else {
    if (white_list.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // next('/page403'); // 否则全部重定向到登录页
      // next('/login'); // 否则全部重定向到登录页
      router.push({
        name: 'login',
        query: {
          returnName: to.name
        }
      })
    }
  }
})

// router.beforeEach((to, from, next) => {
//   iView.LoadingBar.start()
//   const token = getToken()
//   if (!token && to.name !== LOGIN_PAGE_NAME) {
//     // 未登录且要跳转的页面不是登录页
//     next({
//       name: LOGIN_PAGE_NAME // 跳转到登录页
//     })
//   } else if (!token && to.name === LOGIN_PAGE_NAME) {
//     // 未登陆且要跳转的页面是登录页
//     next() // 跳转
//   } else if (token && to.name === LOGIN_PAGE_NAME) {
//     // 已登录且要跳转的页面是登录页
//     next({
//       name: homeName // 跳转到homeName页
//     })
//   } else {
//     if (store.state.user.hasGetInfo) {
//       turnTo(to, store.state.user.access, next)
//     } else {
//       store.dispatch('getUserInfo').then(user => {
//         // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
//         turnTo(to, user.access, next)
//       }).catch(() => {
//         setToken('')
//         next({
//           name: 'login'
//         })
//       })
//     }
//   }
// })

router.afterEach(to => {
  setTitle(to, router.app)
  iview.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
